package ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

import define.Config;

@SuppressWarnings("serial")
public class Popup extends JDialog implements MouseListener, WindowListener, KeyListener
{
	private JTextField m_text;
	private JButton m_yes;
	private JButton m_no;
	private JPanel m_downPanel;
	private PopupListener m_listener;
	private String m_sendText;
	
	public Popup(JFrame mainFrame, String title, String text, PopupListener listener)
	{
		super(mainFrame, title, true);
		m_listener = listener;
		m_text = new JTextField();
		m_text.setText(text);
		m_text.selectAll();
		m_text.addKeyListener(this);
		m_yes = new JButton("ok");
		m_no = new JButton("cancel");
		m_yes.addMouseListener(this);
		m_no.addMouseListener(this);
		this.setLayout(new BorderLayout());
		this.add(m_text, BorderLayout.CENTER);
		m_downPanel = new JPanel();
		m_downPanel.setLayout(new FlowLayout());
		this.add(m_downPanel, BorderLayout.SOUTH);
		m_downPanel.add(m_yes);
		m_downPanel.add(m_no);
		this.setSize(Config.POPUP_W, Config.POPUP_H);
		this.setVisible(true);
		this.addWindowListener(this);
	}

	public void mouseClicked(MouseEvent e) 
	{
		Object s = e.getSource();
		if(s == m_yes)
		{
			m_sendText = m_text.getText();
		}
		else 
		{
			m_sendText = null;
		}
		this.dispose();
	}

	public void mouseEntered(MouseEvent arg0) 
	{
	}

	public void mouseExited(MouseEvent arg0) 
	{
	}

	public void mousePressed(MouseEvent arg0) 
	{	
	}

	public void mouseReleased(MouseEvent arg0) 
	{
	}

	public void windowActivated(WindowEvent e)
	{	
	}

	public void windowClosed(WindowEvent e) 
	{
	}

	public void windowClosing(WindowEvent e)
	{
	}

	public void windowDeactivated(WindowEvent e)
	{
		m_listener.onClose(m_sendText);
	}

	public void windowDeiconified(WindowEvent e)
	{
	}

	public void windowIconified(WindowEvent e)
	{
	}

	public void windowOpened(WindowEvent e)
	{
	}

	public void keyPressed(KeyEvent e) 
	{
	}

	public void keyReleased(KeyEvent e)
	{
		if(e.getKeyCode() == KeyEvent.VK_ENTER)
		{
			m_sendText = m_text.getText();
			this.dispose();
		}
		else if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
		{
			m_sendText = null;
			this.dispose();
		}
	}

	public void keyTyped(KeyEvent e) 
	{
	}
}
